﻿using Microsoft.Extensions.Hosting;
using RabbitMQ.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace RabbitMqDemo.HosteServices
{
    public class RabbitMqProduct : IHostedService
    {
        Task task = null;
        public Task StartAsync(CancellationToken cancellationToken)
        {
            task = Task.Run(() =>
            {
                ConnectionFactory factory = new ConnectionFactory();
                factory.UserName = "admin-test";
                factory.Password = "123456";
                factory.VirtualHost = "/";
                factory.HostName = "192.168.2.113";
                factory.Port = 5672;

                using (IConnection connection = factory.CreateConnection())
                {
                    using (var channel = connection.CreateModel())
                    {
                        var exchangeName = "my.test";
                        var routingKey = "*";
                        string queue = string.Format("MqTest");
                        channel.ExchangeDeclare(exchangeName, ExchangeType.Topic);
                        channel.QueueDeclare(queue, false, false, false, null);   //定义一个队列
                        channel.QueueBind(queue, exchangeName, routingKey);
                        var properties = channel.CreateBasicProperties();
                        properties.Persistent = true;
                        while (cancellationToken.IsCancellationRequested==false)
                        {
                            Console.Write("请输入要发送的消息：");
                            var message = Console.ReadLine();
                            var body = Encoding.UTF8.GetBytes(message);

                            channel.BasicPublish(exchangeName, routingKey, properties, body); //发送消息

                            Console.WriteLine("已发送的消息： {0}", message);
                        }
                    }
                }
            }, cancellationToken);
            return Task.CompletedTask;
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            return Task.CompletedTask;
        }
    }
}
